//
//  ZDVCommentViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/3/22.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZDVCommentViewController.h"
// 视频详情的评论
#import "ZCommentTableViewCell.h"
#import "ZPostCommentView.h"
#import "TacticsDetailModel.h"
#import "SPPlaceholderCell.h"

#import "ZPostCommentView.h"

static NSString *const placeCellID = @"placeholders";
static NSString * const ZDiscussViewIdentifier = @"ZDiscussViewIdentifier";
static int _page = 1;
@interface ZDVCommentViewController ()<UITableViewDataSource,UITableViewDelegate>{
    UITableView * _maintableView;
    LZUserInfo *userInfo;
    ZPostCommentView * _postView;
}
/** 评论数据数组 */
@property (nonatomic, strong) NSMutableArray <TacticsDetailModel*>*commentArray;
@property (nonatomic,assign) BOOL isHaveData;
@end

@implementation ZDVCommentViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([userInfo.uid isEqualToString:@""] || userInfo.uid == nil) {
        [self remakeConstraints];
    }else {
        [self appearComment];
    }
}
// 修改tableView和评论栏的约束（游客模式）
- (void)remakeConstraints {
    [_maintableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    _postView.hidden = YES;
}
// 登录模式显示评论栏
- (void)appearComment {
    _maintableView.frame = CGRectMake(0, 0,SCREEN_Width, SCREEN_Height-129*ysIZE);
    _postView.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _commentArray = [NSMutableArray array];
    userInfo = [LZUserInfo getUserInfo];
    self.isHaveData = YES;
    [self initlizeInterface];
    [self pullDownData];
    
    
}

- (void)initlizeInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    _maintableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _maintableView.dataSource = self;
    _maintableView.delegate = self;
//    _maintableView.rowHeight = 85 * ysIZE;
    _maintableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_maintableView registerClass:[ZCommentTableViewCell class] forCellReuseIdentifier:ZDiscussViewIdentifier];
     [_maintableView registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    
    //创建发布评论一栏
    _postView = [[ZPostCommentView alloc] init];
    [_postView.postBtn  addTarget:self action:@selector(postCommet) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_maintableView];
    [self.view addSubview:_postView];
    [_postView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.bottom.equalTo(self.view);
        make.height.offset(45*ysIZE);
    }];
    
    // 上拉加载下拉刷新
    __weak typeof(self) weakSelf = self;
    _maintableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [_maintableView.mj_header endRefreshing];
    }];
    _maintableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
        [_maintableView.mj_footer endRefreshing];
    }];
    
    [_maintableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(_postView.mas_top);
    }];
    
    
}

//表格协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {
    return self.isHaveData? _commentArray.count :1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData) {
        ZCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ZDiscussViewIdentifier forIndexPath:indexPath];
        cell.tacticsDetailModel = _commentArray[indexPath.row];
        cell.selectionStyle = 0 ;
        return cell;
    }
    else {
        SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        return 85*ysIZE;
    }else {
        return  SCREEN_Height-104;
    }
}

// 下拉刷新方法
- (void)pullDownData {
    // 下拉刷新之前清除之前的数据
    _page = 1;
    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page],@"vid":self.vid};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Consult/moreVideoCmt" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"评论下拉刷新----%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealDataWithDict:dict];
            
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
            self.isHaveData = NO;
            [_maintableView reloadData];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
        self.isHaveData = NO;
        [_maintableView reloadData];
        LZLog(@"%@",error);
    }];
    
    
}

// 上拉加载方法
- (void)loadMoreData {
    _page++;
    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page],@"vid":self.vid};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Consult/moreVideoCmt" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"就医策略详情上拉数据----%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealPullUpDataWithDict:dict];
            //[weakSelf setValueWithDict:dict];
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
            
        }
    } failure:^(NSError *error) {
        LZLog(@"%@",error);
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];
}

// 拿到数据以后处理下拉刷新方法
- (void)dealDataWithDict:(NSDictionary *)dict {
    [_maintableView.mj_footer resetNoMoreData];
    [_commentArray removeAllObjects];
    NSArray *tempArr = dict[@"list"];
    if (tempArr.count == 0) {
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        self.isHaveData = NO;
        [_maintableView.mj_footer endRefreshingWithNoMoreData];
        
    }else if (tempArr.count < 10) {
//        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [_maintableView.mj_footer endRefreshingWithNoMoreData];
    }
    
    
    for (NSDictionary *dict in tempArr) {
        TacticsDetailModel *commentItem = [[TacticsDetailModel alloc] initWithDict:[dict mutableCopy]];
        [_commentArray addObject:commentItem];
    }
    [_maintableView reloadData];
}


// 处理上拉加载方法
- (void)dealPullUpDataWithDict:(NSDictionary *)dict {
    [_maintableView.mj_footer resetNoMoreData];
    NSArray *tempArr = dict[@"list"];
    if (tempArr.count == 0) {
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        [_maintableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }else if (tempArr.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [_maintableView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSDictionary *dict in tempArr) {
            TacticsDetailModel *commentItem = [[TacticsDetailModel alloc] initWithDict:[dict mutableCopy]];
            [_commentArray addObject:commentItem];
    }
    [_maintableView reloadData];
}


// 发布按钮的方法
- (void)postCommet {
    if ([_postView.commentField.text isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"评论不可以为空~" inView:self.view];
        return;
    }
        // 引号转换
    NSString * comText = [_postView.commentField.text stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
    
    if (!_vid || [_vid isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"没有视频id" inView:self.view];
        return;
    }
    NSDictionary *paramas = @{@"vid":_vid,@"uid":userInfo.uid,@"content":comText};
        [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/addArticleCmt" sucessBlock:^(id content) {
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
            LZLog(@"--视频评论里面那层--发表评论数据----%@",dict);
            if ([dict[@"code"] intValue] == 1) {
                [YJProgressHUD showMessage:@"评论成功" inView:self.view];
                // 评论textfield失去第一响应并且刷新数据
                _postView.commentField.text = @"";
                [_postView.commentField resignFirstResponder];
                [_maintableView.mj_header beginRefreshing];
    
            }else if ([dict[@"code"] intValue] == 0) {
                [YJProgressHUD showMessage:@"评论失败" inView:self.view];
            }
        } failure:^(NSError *error) {
            [YJProgressHUD showMessage:@"评论失败" inView:self.view];
        }];
    
}



@end
